<script setup lang="ts">
import type { EChartsOption } from 'echarts';

import { onMounted, onUnmounted, ref, watch } from 'vue';

import * as echarts from 'echarts';

interface ChartDataItem {
  name: string;
  organization?: string;
  value: number;
}

const props = defineProps<{
  chartData: ChartDataItem[];
  type: 'organization' | 'personal';
}>();

const chartRef = ref<HTMLElement>();
let chart: echarts.ECharts | null = null;

const COLOR_LIST = ['#4B79E4', '#43BF7D', '#F6B044', '#E772BB', '#8463E9'];

const getOptions = (): EChartsOption => ({
  backgroundColor: 'transparent',
  tooltip: {
    trigger: 'item',
  },
  legend: {
    orient: 'vertical',
    left: 0,
    top: 'center',
    itemWidth: 15,
    itemHeight: 15,
    icon: 'rect',
    textStyle: {
      color: '#fff',
      fontSize: 14,
    },
  },
  series: [
    {
      type: 'pie',
      radius: ['50%', '70%'],
      center: ['65%', '50%'],
      label: {
        show: false,
        position: 'center',
      },
      labelLine: { show: false },
      emphasis: {
        label: {
          show: true,
          fontSize: 40,
          fontWeight: 'bold',
          color: '#7cffb2',
          formatter: (params: any) => {
            return `${params.value}`;
          },
        },
      },
      data: props.chartData.map((item, index) => ({
        name:
          props.type === 'personal'
            ? `${item.name}--${item.organization}`
            : item.name,
        value: item.value,
        itemStyle: {
          color: COLOR_LIST[index % COLOR_LIST.length],
        },
      })),
    },
  ],
});

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  chart = echarts.init(chartRef.value);
  chart.setOption(getOptions());

  // 添加鼠标事件
  chart.on('mouseover', { seriesIndex: 0 }, (params: any) => {
    chart?.setOption({
      series: [
        {},
        {
          data: [
            {
              label: {
                formatter: () => {
                  return `{value|${params.value}}`;
                },
              },
            },
          ],
        },
      ],
    });
  });

  // 鼠标移出时恢复默认显示
  chart.on('mouseout', { seriesIndex: 0 }, () => {
    chart?.setOption({
      series: [
        {},
        {
          data: [
            {
              label: {
                formatter: () => {
                  return '{value|0}';
                },
              },
            },
          ],
        },
      ],
    });
  });
};

// 监听数据变化
watch(
  () => props.chartData,
  () => {
    chart?.setOption(getOptions());
  },
  { deep: true },
);

// 监听窗口大小变化
const handleResize = () => {
  chart?.resize();
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  chart?.dispose();
});
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 270px"></div>
</template>
